/****************************************************
 *   Read more link                                    *
 ****************************************************/

/*global $: false, javascriptSpecificClassName: false */

$(document).ready(function () {
    "use strict";

    function removeReadMoreRelatedElements(contentGroupContainer) {
        contentGroupContainer.find(".readMoreHidden").remove();
        contentGroupContainer.find(".readMore").remove();
    }

    /**
     * This function calculates which paragraph contains the character limit
     * and inside that paragraph, how many characters it has before the limit.
     */
    function collectSplittingParagraphData(paragraphs, charLimit) {
        var indexOfSplittingParagraph = null,
            numberOfCharactersBeforeCharLimit = 0,
            charCounter = 0,
            currentParagraphLength;

        paragraphs.each(function (index) {
            if (indexOfSplittingParagraph === null) {
                currentParagraphLength = $(this).text().length;
                if (charCounter + currentParagraphLength >= charLimit) {
                    indexOfSplittingParagraph = index;
                    numberOfCharactersBeforeCharLimit = charLimit - charCounter;
                } else {
                    charCounter += currentParagraphLength;
                }
            }
        });

        return {
            index: indexOfSplittingParagraph,
            charsBeforeLimit: numberOfCharactersBeforeCharLimit
        };
    }

    /**
     * Search the first place in a text from the startPoint, where the text
     * can be split (space, dot etc.)
     */
    function searchSplittingPoint(text, startPoint) {
        var splitterChars = [ " ", ".", "?", "!", ",", ";" ],
            searching = true,
            i;
        for (i = startPoint; i < text.length && searching; i += 1) {
            if ($.inArray(text.charAt(i), splitterChars)) {
                return i;
            }
        }
    }

    /**
     * In the paragraph where the character limit can be found it hides the
     * remaining text and insert an ellipse.
     */
    function hideRemainingPartsOfSplittinParagraph(paragraphs, splittingParagraphData) {
        var paragraphToSplit = paragraphs.eq(splittingParagraphData.index),
            textOfParagraphToSplit = paragraphToSplit.text(),

            whereToSplit = searchSplittingPoint(textOfParagraphToSplit, splittingParagraphData.charsBeforeLimit),
            visibleText,
            textToHide,
            ellipseSpan,
            hiddenSpan;

        if (whereToSplit < textOfParagraphToSplit.length - 1) {
            visibleText = textOfParagraphToSplit.substr(0, whereToSplit);
            textToHide = textOfParagraphToSplit.substr(whereToSplit);

            ellipseSpan = $("<span>", { 'class': 'ellipse' });
            ellipseSpan.html("&hellip;");

            hiddenSpan = $("<span>", { 'class': 'hiddenText'});
            hiddenSpan.text(textToHide);

            paragraphToSplit.html(visibleText);
            paragraphToSplit.append(ellipseSpan);
            paragraphToSplit.append(hiddenSpan);

        }
    }

    /**
     * Hide the paragraphs which are after the 'splitting paragraph', so
     * the paragraph which contains the character limit.
     */
    function hideParagraphsAfterSplittingParagraph(contentGroupContainer, splittinParagraphData) {
        var paragraphsToHide = contentGroupContainer.find("p:gt(" + splittinParagraphData.index + ")");
        contentGroupContainer.find(".readMoreHidden").append(paragraphsToHide);
    }


    /*
     * Prepare Content Group read more functionality and hide the
     * text which is overflow the given character limit.
     *
     */
    $(".contentGroupContainer").each(function () {
        if (!$(this).hasClass(javascriptSpecificClassName)) {
            removeReadMoreRelatedElements($(this));
            return false;
        }

        var charLimit = parseInt($(this).attr("data-character-limit"), 10),
            paragraphs = $(this).find("p"),
            charSum = paragraphs.text().length,
            splittingParagraphData;

        if (charLimit !== 0 && charSum > charLimit) {

            splittingParagraphData = collectSplittingParagraphData(paragraphs, charLimit);

            hideRemainingPartsOfSplittinParagraph(paragraphs, splittingParagraphData);

            hideParagraphsAfterSplittingParagraph($(this), splittingParagraphData);

            $(this).find(".readMore").fadeIn();
        } else {
            removeReadMoreRelatedElements($(this));
        }

    });


    $(".readMore").click(function () {

        var contentGroupContainer, linkText;

        if ($(this).find(".plusMinus").text() === " [+]") {


            contentGroupContainer = $(this).parent();
            linkText = contentGroupContainer.attr("data-close");

            contentGroupContainer.find(".ellipse").hide();
            contentGroupContainer.find(".hiddenText").stop(true, true).fadeIn();
            contentGroupContainer.find(".readMoreHidden").stop(true, true).slideDown();


            $(this).find(".text").text(linkText);
            $(this).find(".plusMinus").text(" [-]");

        }
        else if ($(this).find(".plusMinus").text() === " [-]") {


            contentGroupContainer = $(this).parent();
            linkText = contentGroupContainer.attr("data-readmore");

            contentGroupContainer.find(".ellipse").stop(true, true).fadeIn();
            contentGroupContainer.find(".hiddenText").hide();
            contentGroupContainer.find(".readMoreHidden").stop(true, true).slideUp();

            $(this).find(".text").text(linkText);
            $(this).find(".plusMinus").text(" [+]");

        }

    });

});



